package com.qsl.consumer;

import com.qsl.entity.User;
import com.qsl.service.UserService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;

import static com.qsl.constant.Constant.QSL_QUEUE;

/**
 * @description: xxx描述
 * @author: 博客园@青石路
 * @date: 2024/1/7 16:11
 */
@Component
@Slf4j
public class QslConsumer implements ChannelAwareMessageListener {

    @Value("${qsl-front.url}")
    private String frontUrl;

    @Resource
    private RestTemplate restTemplate;
    @Resource
    private UserService userService;

    @Override
    @RabbitListener(queues = QSL_QUEUE)
    public void onMessage(Message message, Channel channel) {
        String userId = new String(message.getBody(), StandardCharsets.UTF_8);
        log.info("收到front消息，userId={}", userId);
        // 1、调接口查询数据
        ResponseEntity<User> userResp = restTemplate.getForEntity(frontUrl.replace("{userId}", userId), User.class);
        if (HttpStatus.OK != userResp.getStatusCode()) {
            log.error("查询front接口失败，status = {}", userResp.getStatusCode());
        } else {
            User user = userResp.getBody();
            log.info("front接口响应值：{}", user);
            userService.saveOrUpdate(user);
        }
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            log.error("消息回复失败，异常信息：", e);
        }
    }
}
